最后一遍-L35-Search Insert Position

描述:

Given a sorted array of distinct integers and a target value, 
return the index if the target is found. 
If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

 

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4
 

Constraints:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104

思路:考察二分法,都是考察的二分法的细节问题,例如二分法的等于的情况,二分法大于,小于的两端的index所处于的位置 这道题目可以出现为考察插入的位置,下一道题目可以考察,插入位置的后一个值是什么? 这次都是:a sorted array of distinct integers 如果不是distinct integers,该如何的做?


public class L35 {
    public static void main(String[] args) {
        System.out.println("Keep moving ,man!");
//        System.out.println(searchInsert(new int[]{1,3,5,6},5));
        System.out.println(searchInsert(new int[]{1,3,5,6,7},2));
        System.out.println(searchInsert(new int[]{1,3,5,6,7},4));
    }

    //https://leetcode.com/problems/search-insert-position/
    //    1 <= nums.length <= 104
    //    -104 <= nums[i] <= 104
    //    nums contains distinct values sorted in ascending order.
    //    -104 <= target <= 104
    public static int searchInsert(int[] nums, int target) {
        if(nums[0] > target) return 0;
        if(nums[nums.length-1] < target) return nums.length;
        int from =0,to=nums.length-1;
        while(from <= to){
            int mid = from+ (to-from)/2;
            if(nums[mid] == target) {
                return mid;
            }else if(nums[mid]  > target){
                to=mid-1;
            }else{
                from= mid+1;
            }
        }
        return from;
    }
}

Powered by andiHappy and Theme by AndiHappy